//
//  Request.swift
//  CooperSwift_Example
//
//  Created by 计海峰 on 2021/6/15.
//  Copyright © 2021 CocoaPods. All rights reserved.
//

import Foundation

import Moya
import SwiftyJSON

extension URLRequest {
    
    /// global common params
    private var commonParams: [String: Any] {
        return ["city": "合肥市"]
    }
    
    /// global common header fields
    private var commonHeaderFields: [String : String] {
        return [:]
    }
    
    mutating func appendCommonParams() -> URLRequest {
        
        let newHeaderFields = (allHTTPHeaderFields ?? [:]).merging(commonHeaderFields) { (current, _) in current }
        allHTTPHeaderFields = newHeaderFields
        
        let request = try? encoded(parameters: commonParams, parameterEncoding: URLEncoding(destination: .queryString))
        assert(request != nil, "append common params failed, please check common params value")
        
        return request!
    }
    
    func encoded(parameters: [String: Any], parameterEncoding: ParameterEncoding) throws -> URLRequest {
        do {
            return try parameterEncoding.encode(self, with: parameters)
        } catch {
            throw MoyaError.parameterEncoding(error)
        }
    }
    
}
